﻿import kliment.net.URLMethod;
import mx.utils.Delegate;
import kliment.data.FormField;
import kliment.data.FastXML;

/**
 * ...
 * @author	Kliment
 * @version	1.2.4
 */
class kliment.data.Form {
	private var _fields:Array;
	private var _request_url:String;
	private var _method:String;
	private var _request:FastXML;
	
	public var onSubmit:Function;/* = function(target:Form, answer:FastXML):Void { }*/
	
	public function Form(fields:Object, request_url:String, method:String) {
		_fields = new Array();
		_request_url = request_url;
		_method = method || URLMethod.POST;
		
		for (var i in fields) 
			addField(fields[i]);
	}
	
	public function submit():Boolean {
		var data:Object = new Object();
		var length:Number = _fields.length
		for (var i:Number = 0; i < length; i++) {
			var fieldName:FormField = _fields[i];
			if (!fieldName.isValid)
				return false;
			data[fieldName.name] = fieldName.value;
		}
		
		_request = new FastXML();
		_request.sendAndLoad(_request_url, data, _method);
		_request.onLoad = Delegate.create(this, _sever_answer);
		return true;
	}
	
	private function _sever_answer(success:Boolean, target:FastXML):Void {
		if (success && _request.status == 0) {
			onSubmit(this, _request);
		} else {
			//onError();
		}
	}
	
	public function addField(value:FormField):Void {
		_fields.push(value);
		value.form = this;
	}
	
	public function clear():Void {
		var i:Number = _fields.length;
		while(i--){
			var fieldName:FormField = _fields[i];
			fieldName.clear();
		}
	}
	
	public function remove():Void {
		while (_fields.length) {
			var item = _fields.shift();
			item.remove();
			item = null;
		}
	}
	
	//public var onError:Function = function():Void { };
}